#员工月工资统计服务类  flydragon
class SalaryMonthStatistics::CompanyStatisticsService
  include HeiPisService

  #company 单位  为空时,统计系统中所有的员工工资
  #month 月份字符串(eg:"2017-01")
  def initialize(company, month)
    @company = company
    @month = month
  end

  #执行方法 返回值
  def call


    flag = true
    start_date = Time.now
    begin

      if @company.present?

        preform(@company)
      else
        Company.all.each do |company|
          preform(company)
        end
      end
      
    rescue Exception => e  
      Rails.logger.info("工资月统计出现异常,信息为:#{e.message}")
      flag = false
    end

    end_date = Time.now

    Rails.logger.info("工资统计消耗#{end_date.to_i-start_date.to_i}秒!")

    flag
  end


  def preform(company)

    company.employees.includes(:employee_of_studios).each do |employee|

        
        result = Employees::MonthSalaryService.call(employee, @month)
        
        position_names = []
        studio_ids = []
        department_ids = []
        employee.employee_of_studios.map{|record|
          position_names << record.position_name
          studio_ids << "(#{record.studio_id})"
          department_ids << "(#{record.department_id})"
        }

        salary_month_statistic = SalaryMonthStatistic.find_or_create_by(company_id: company.id,employee_id: employee.id,month: @month)
        salary_month_statistic.base_salary = result.base_salary
        salary_month_statistic.commission_salary = result.commission_salary
        salary_month_statistic.sum_salary = result.sum_salary
        salary_month_statistic.position_names = position_names.uniq.join(',')
        salary_month_statistic.employee_name = employee.name
        salary_month_statistic.studio_ids = studio_ids.uniq.join(',')
        salary_month_statistic.department_ids = department_ids.uniq.join(',')
        
        salary_month_statistic.save
      end
  end
  
end
